﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections.Generic;
using MS.InformationManagement.DAL.DocumentCenter;
using System.Linq;
using Microsoft.SharePoint;
using MS.InformationManagement.Support;
using System.IO;
using MS.InformationManagement.Presenter.Support;

namespace MS.InformationManagement.Controls._CONTROLTEMPLATES.InformationManagerControls
{
    public partial class UploadFilesControl : BaseControl
    {

        #region fields

        bool _enable = true;

        #endregion

        #region Properties

        public bool AllowInboxSelection { get; set; }

        public bool LocalFilesOnly { get; set; }

        public bool LibraryFilesOnly
        {
            set
            {
                if (value)
                {
                    ddlTipoUploadFile.SelectedValue = "BIBLIOTECA";
                    ddlTipoUploadFile.Enabled = false;
                    divFileSistem.Visible = false;
                    divLibrary.Visible = true;
                }
            }
        }

        public bool Requered { get; set; }

        public bool Enable
        {
            set
            {
                fileUploadControl.Visible = value;
                btnAddFile.Visible = value;
                ddlTipoUploadFile.Visible = value;
                ImageButton1.Visible = value;
                _enable = value;
            }
            get
            {
                return _enable;
            }
        }

        public bool ShowFileSelector
        {
            set
            {
                fileUploadControl.Visible = value;
                btnAddFile.Visible = value;
                ImageButton1.Visible = value;
                ddlTipoUploadFile.Visible = value;
            }
        }

        public bool isMainDocument { get; set; }

        public List<FileEntity> Files
        {
            get
            {
                if (Cache[SPContext.Current.Web.CurrentUser.LoginName.GetUserWithOutDomain() + "files"] == null)
                    Cache[SPContext.Current.Web.CurrentUser.LoginName.GetUserWithOutDomain() + "files"] = new List<FileEntity>();
                return Cache[SPContext.Current.Web.CurrentUser.LoginName.GetUserWithOutDomain() + "files"] as List<FileEntity>;
            }
            set
            {
                Cache[SPContext.Current.Web.CurrentUser.LoginName.GetUserWithOutDomain() + "files"] = value;
                Enable = false;
            }
        }

        //public override event ErrorHandler OnError;

        public string Strategy
        {
            get { return Page.Request.QueryString["strategy"]; }
        }

        #endregion

        #region Form Actions

        protected void lnkShowFile_DataBinding(object sender, EventArgs e)
        {
            HyperLink trigger = sender as HyperLink;
            trigger.NavigateUrl = string.Format("/sites/docs/_layouts/MS.InformationManagement.Controls/FileViewer.aspx?FileName={0}", Server.UrlEncode(trigger.NavigateUrl));
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            Page.RegisterAjaxLoaderPlugin();
            btnAddFile.AddLoader();
            this.uploadFileError.Visible = false;

            ddlTipoUploadFile.Items.Add(new ListItem() { Text = "ARCHIVO SISTEMA", Value = "SISTEMA" });
            if (!AllowInboxSelection)
            {
                ddlTipoUploadFile.Items.Add(new ListItem() { Text = "BIBLIOTECA", Value = "BIBLIOTECA" });
                ddlTipoUploadFile.Enabled = true;
            }
            else
                ddlTipoUploadFile.Enabled = false;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            lblError.Text = string.Empty;
            int mainDocument = isMainDocument ? 1 : 0;
            string url = string.Empty;
            if (isMainDocument)
                url = string.Format("javascript:openDialogAutoSize('" + SPContext.Current.Web.Url + "/_layouts/MS.InformationManagement.Controls/SelectFileLibrary.aspx?isMainDocument=" + mainDocument + "&numSelect=1&ParentId={0}');return false;",this.ID);
            else
                url = string.Format("javascript:openDialogAutoSize('" + SPContext.Current.Web.Url + "/_layouts/MS.InformationManagement.Controls/SelectFileLibrary.aspx?isMainDocument=" + mainDocument + "&numSelect=0&ParentId={0}');return false;",this.ID);
            ImageButton1.Attributes.Add("onclick", url);

            //if (Cache["SelectedFiles" + mainDocument] != null)
            //{
            //    if (isMainDocument)
            //        Files.RemoveAll(x => x.IsMainDocument.Equals(isMainDocument));

            //    Files.AddRange((List<FileEntity>)Cache["SelectedFiles" + mainDocument]);
            //    Cache.Remove("SelectedFiles" + mainDocument);
            //}
            loadData();

            uploadFileError.InnerText = "";
            if (IsPostBack) return;


            if (Strategy != "view" && Strategy != "edit" && Strategy != "UpdateRemitente" && Strategy != "UpdateCopy")
                Cache.Remove(this.ID + SPContext.Current.Web.CurrentUser.LoginName.GetUserWithOutDomain() + "files");
        }

        protected void gvFiles_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if (!_enable)
                    e.Row.Cells[3].Visible = false;
            }

        }

        protected void UPloadAction(object sender, EventArgs e)
        {
            try
            {
                var fileName = (from currentFile in Files
                                where currentFile.FileName == fileUploadControl.FileName
                                select currentFile).FirstOrDefault();
                if (fileName != null) throw new Exception("Archivo ya existe");

                int index = fileUploadControl.FileName.LastIndexOf('.');
                string extension = fileUploadControl.FileName.Substring(index + 1).ToLower();
                if (IsOfficeFile(extension))
                {
                    CheckFile(extension);
                    if (isMainDocument) { Files.RemoveAll(x => x.IsMainDocument.Equals(isMainDocument)); }
                    Files.Add(new FileEntity() { IsMainDocument = isMainDocument, CreationDate = DateTime.Now, FileName = fileUploadControl.FileName, FileSize = fileUploadControl.FileBytes.Length / 1024, FileContent = fileUploadControl.FileBytes });
                }
                else
                {
                    if (isMainDocument) { Files.RemoveAll(x => x.IsMainDocument.Equals(isMainDocument)); }
                    Files.Add(new FileEntity() { IsMainDocument = isMainDocument, CreationDate = DateTime.Now, FileName = fileUploadControl.FileName, FileSize = fileUploadControl.FileBytes.Length / 1024, FileContent = fileUploadControl.FileBytes });
                }

                this.loadData();
            }
            catch (Exception ex)
            {
                HandleError(ex);
                //ShowErrorMessage(ex.Message);
            }
        }

        protected void delete_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                ImageButton currentButton = sender as ImageButton;
                if (currentButton == null) return;
                Files.Remove((from file in Files
                              where file.FileName == currentButton.CommandArgument
                              select file).FirstOrDefault());
                this.loadData();
            }
            catch (Exception ex)
            {
                HandleError(ex);
                //OnError(this, ex);
            }
        }

        protected void showFile(object sender, ImageClickEventArgs e)
        {
            ImageButton currentButton = sender as ImageButton;
            if (currentButton == null) return;
            var file = (from fl in Files
                        where fl.FileName == currentButton.CommandArgument
                        select fl).FirstOrDefault();
            Response.AppendHeader("content-disposition", "attachment;filename=" + currentButton.CommandArgument);
            Response.OutputStream.Write(file.FileContent, 0, file.FileContent.Length);
        }

        protected void ddlTipoUploadFile_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlTipoUploadFile.SelectedItem.Text == "ARCHIVO SISTEMA")
            {
                divFileSistem.Visible = true;
                divLibrary.Visible = false;
            }
            else
            {
                divFileSistem.Visible = false;
                divLibrary.Visible = true;
            }
        }


        #endregion

        #region Private Methods

        private void showMessage(string message)
        {
            lblError.Text = message;
        }

        public void loadData()
        {
            List<FileEntity> fileColl = new List<FileEntity>();
            var _file = Files.Where(x => x.IsMainDocument.Equals(isMainDocument)).FirstOrDefault();

            if (isMainDocument && _file != null)
                fileColl.Add(_file);
            else
                fileColl.AddRange(Files.Where(x => x.IsMainDocument.Equals(isMainDocument)));

            gvFiles.DataSource = fileColl;
            gvFiles.DataBind();
        }

        #endregion

        private void CheckFile(string fileExtension)
        {
            byte[] data = new byte[(Int32)fileUploadControl.PostedFile.InputStream.Length];
            fileUploadControl.PostedFile.InputStream.Read(data, 0, (Int32)fileUploadControl.PostedFile.InputStream.Length);
            using (MemoryStream officeFileStream = new MemoryStream())
            {
                officeFileStream.Write(data, 0, data.Length);
                OfficeWordHelper.RemoveCoreProperties(officeFileStream, fileExtension);
                data = new byte[officeFileStream.Length];
                officeFileStream.Read(data, 0, (Int32)officeFileStream.Length);
            }
        }

        private bool IsOfficeFile(string extension)
        {

            return extension.Equals("pptx") || extension.Equals("docx") || extension.Equals("xlsx") || extension.Equals("ppt") || extension.Equals("doc") || extension.Equals("xls");
        }

        private void ShowErrorMessage(string message)
        {
            this.uploadFileError.Visible = true;
            this.uploadFileError.InnerText = message;
        }
    }

}
